package com.example.mobiletest.service

import android.content.Context
import com.example.mobiletest.model.*
import com.google.gson.Gson
import kotlinx.coroutines.delay
import kotlin.random.Random

class BookingServiceImpl(private val context: Context) : BookingService {
    
    private val gson = Gson()
    
    override suspend fun getBookingData(): Booking? {
        return try {
            // 模拟网络延迟
            delay(Random.nextLong(500, 2000))
            
            // 模拟网络可能失败的情况（10%失败率）
            if (Random.nextFloat() < 0.1f) {
                throw Exception("Network error simulation")
            }
            
            // 从raw资源文件读取JSON数据
            val inputStream = context.resources.openRawResource(
                context.resources.getIdentifier("booking", "raw", context.packageName)
            )
            val jsonString = inputStream.bufferedReader().use { it.readText() }
            
            // 解析JSON并添加当前时间戳
            val booking = gson.fromJson(jsonString, Booking::class.java)
            booking.copy(cacheTime = System.currentTimeMillis())
            
        } catch (e: Exception) {
            println("BookingService: Error fetching booking data - ${e.message}")
            null
        }
    }
    
    override suspend fun refreshBookingData(): Booking? {
        println("BookingService: Refreshing booking data...")
        return getBookingData()
    }
}